package com.tql.hualala.service;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.web.domain.CommonEntity;
import com.ruoyi.common.datasource.annotation.Slave;
import com.tql.hualala.HuaLaLaApi;
import com.tql.hualala.bean.BillDetailBean;
import com.tql.hualala.bean.FoodDetailBean;
import com.tql.hualala.bean.FoodDetailReportDayBean;
import com.tql.hualala.bean.ShopBillDetailBean;
import com.tql.hualala.mapper.HllShopBillDetailMapper;
import com.tql.hualala.request.FoodItem;
import com.tql.hualala.request.HllBillRequest;
import com.tql.hualala.request.Master;
import com.tql.hualala.util.CommonUtil;
import com.tql.hualala.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;



@Service
public class HualalaBillFoodService {
    Logger logger= LoggerFactory.getLogger(this.getClass());
@Autowired
   private HllShopBillDetailMapper shopBillDetailMapper;
    @Autowired
    private HualalaShopService hualalaShopService;
    /**
     *
     * @param shopId
     * @param reportDate 20240101
     */
    @Transactional
    @Slave
    public void saveShopBillDetail(Long shopId,Long reportDate) throws ParseException {
        int month= TimeUtil.getMonth(reportDate);
        String billTableName=CommonUtil.TableName_ShopBillDetail+month;
        String billFoodTableName=CommonUtil.TableName_ShopBillFoodDetail+month;
       // String billFoodReportDayTableName=CommonUtil.TableName_ShopBillFoodReportDayDetail+month;
        List<ShopBillDetailBean> list=  HuaLaLaApi.getShopBillDetail(CommonUtil.GROUP_ID, shopId, reportDate);
        if(null!=list &&list.size()>0)
        for(ShopBillDetailBean bean:list)
        {
            BillDetailBean eachBill= bean.getBillDetailBean();
            List<FoodDetailBean> list_FoodDetailBean=bean.getFoodDetailBeanList();
            //foodCode,reportDate,ShopId
            List<FoodDetailReportDayBean> list_FoodDetailReportBean=getFoodDetailReportDayBean(list_FoodDetailBean,reportDate,shopId);

            //以防万一重复录入  //删掉主表Bill      //删掉子表Food
            String saasOrderKey=eachBill.getSaasOrderKey();
            shopBillDetailMapper.deleteBill(saasOrderKey,billTableName);
            shopBillDetailMapper.deleteBillFood(saasOrderKey,billFoodTableName);

            //插入对应的月份表
            shopBillDetailMapper.insertBillDetailBean(eachBill,billTableName);
            shopBillDetailMapper.insertBillFoodDetailBean(list_FoodDetailBean,billFoodTableName);
           // shopBillDetailMapper.insertBillFoodDetailReportDayBean(list_FoodDetailReportBean,billFoodReportDayTableName);
        }

    }


    /**

     * @param list_FoodDetailBean
     * @param reportDate
     * @return
     */

public List<FoodDetailReportDayBean>  getFoodDetailReportDayBean(List<FoodDetailBean> list_FoodDetailBean ,Long reportDate,Long shopId)
{
    if(CollectionUtils.isEmpty(list_FoodDetailBean))return null;
    List<FoodDetailReportDayBean>  list=list_FoodDetailBean.stream().map(
            each->new FoodDetailReportDayBean(each.getFoodName(),
                    each.getFoodCode(),
                    each.getReportDate(),
                    each.getShopID())).collect(Collectors.toList());
    return list;
}

    @Transactional
    @Slave
    public void handleParam(String data, List<String> shops,String traceId) throws Exception {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<HllBillRequest>>() {}.getType();
        List<HllBillRequest> rootList = gson.fromJson(data, listType);

        if(null!=rootList&&rootList.size()>0)
        {

            for(HllBillRequest bill:rootList)
            {
                //判断一下那些开通的店，当前店是否在
                Master master=bill.getMaster();
                String shopId=master.getShopID().toString();
                boolean flag=shops.contains(shopId);
                if(!flag)
                    insertBillAndBillFood(bill,traceId);

            }



        }



    }




    private void insertBillAndBillFood(HllBillRequest bill,String traceId) throws Exception {

            Long reportDate=TimeUtil.getCurrentDate();
            int month= TimeUtil.getMonth(reportDate);
            String billTableName=CommonUtil.TableName_ShopBillDetail+month;
            String billFoodTableName=CommonUtil.TableName_ShopBillFoodDetail+month;
            Master master=bill.getMaster();
            List<FoodItem> foods=bill.getFoodLst();
            foods.stream().forEach(e-> System.out.println(e.toString()));
            String uuid= UUID.randomUUID().toString();
            BillDetailBean bean=transferBillDetailBean(master,uuid);
            List<FoodDetailBean> list=transferFoodDetailBean(foods,uuid);
            System.out.println("---traceId==---{}"+traceId);
            list.stream().forEach(e-> System.out.println(e.toString()));
            proInsertBillAndBillFood( bean,  billTableName, list, billFoodTableName);


    }
    /**
     * https://blog.csdn.net/weixin_42396963/article/details/132999812
     @Slave  @Transactional一起用无法切换数据源
     */
 @Slave
   // @DS("slave")
  //  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
 // @Transactional
//    @DSTransactional
//    @DS("slave")
//    @DS("slave") //切换数据源
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void proInsertBillAndBillFood(BillDetailBean bean, String billTableName,List<FoodDetailBean> list,String billFoodTableName)
    {
        System.out.println("----------------test---------------");
        shopBillDetailMapper.insertBillDetailBean(bean,billTableName);
        shopBillDetailMapper.insertBillFoodDetailBean(list,billFoodTableName);
    }

    @Slave
    public void saveShopBillReport(int flag, Long reportDate) {
        int month= 0;
        try {
            if(flag==1)
            month = TimeUtil.getMonth1(reportDate);
            if(flag==2)
                month = TimeUtil.getMonth(reportDate);
            if(flag==3) {
                flag = 2;
                month = TimeUtil.getMonth(reportDate);
            }

        String billFoodReportTableName=CommonUtil.TableName_ShopBillFoodReportDayDetail+month;
        String billFoodTableName=CommonUtil.TableName_ShopBillFoodDetail+month;
            System.out.println("billFoodReportTableName:{}-"+billFoodReportTableName+"--billFoodTableName:{}"+billFoodTableName);
            shopBillDetailMapper.saveShopBillReport(flag,reportDate,billFoodReportTableName,billFoodTableName);
            shopBillDetailMapper.updateShopBill(flag,reportDate,billFoodTableName);
        } catch (Exception e) {
            logger.info("saveShopBillReport-flag:{}---reportDate:{}---"+e.getMessage(),flag,reportDate);
            throw new RuntimeException(e);
        }
    }

    private List<FoodDetailBean> transferFoodDetailBean(List<FoodItem> foods,String uuid) {
        if(CollectionUtils.isEmpty(foods))return null;
        List<FoodDetailBean> list=   foods.stream().map(food->{
            FoodDetailBean bean=new FoodDetailBean();
            bean.setActionTime(food.getActionTime());
            bean.setReportDate(food.getReportDate());
            bean.setFoodCategoryName(food.getFoodCategoryName());

            bean.setFoodCategoryKey(food.getFoodCategoryKey());
            bean.setFoodCode(food.getFoodCode());
            bean.setFoodName(food.getFoodName());
            bean.setFoodKey(food.getFoodKey());
            bean.setFoodProPrice(food.getFoodProPrice().toString());
            bean.setFoodPayPrice(food.getFoodPayPrice().toString());
            bean.setFoodRealPrice(food.getFoodRealPrice().toString());
            bean.setFoodRealAmount(food.getFoodRealAmount().toString());
            bean.setFoodPriceAmount(food.getFoodPriceAmount().toString());
            bean.setIsSFDetail(food.getIsSFDetail());
            bean.setIsSetFood(food.getIsSetFood());
            bean.setItemKey(food.getItemKey());

            bean.setOrderStatus(food.getOrderStatus());
            bean.setOrderSubType(food.getOrderSubType());
            bean.setSaasOrderKey(food.getOrderKey());
            Long shopID=Long.parseLong(food.getShopID());
            bean.setShopID(shopID);
            bean.setShopName(food.getShopName());
            bean.setUnit(food.getUnit());
            bean.setUnitAdjuvant(food.getUnitAdjuvant());
            bean.setUnitKey(food.getUnitKey());
            bean.setUnitAdjuvantNumber(food.getUnitAdjuvantNumber());
            bean.setUuid(uuid);
            return bean;
        }) .collect(Collectors.toList());
        return list;
    }

    private BillDetailBean transferBillDetailBean(Master master,String uuid) {
        BillDetailBean bean=new BillDetailBean();
        bean.setActionTime(master.getActionTime());
        bean.setGroupID(master.getGroupID());
        bean.setShopID(master.getShopID());
        bean.setShopName(master.getShopName());
        bean.setReportDate(master.getReportDate());
        bean.setSaasOrderKey(master.getOrderKey());
        bean.setOrderStatus(master.getOrderStatus());
        bean.setSaasOrderNo(master.getOrderNo());
        bean.setFoodAmount(master.getFoodAmount().toString());
        bean.setPromotionAmount(master.getPromotionAmount().toString());
        bean.setPaidAmount(master.getPaidAmount().toString());
        bean.setCheckoutTime(master.getCheckoutTime());
        bean.setUuid(uuid);
        return bean;
    }


//    public void saveHllShopBillFoodReportday(CommonEntity entity) {
//    int flag= entity.getFlag();
//
//        String billFoodReportTableName=CommonUtil.TableName_ShopBillFoodReportDayDetail+month;
//        shopBillDetailMapper.saveHllShopBillFoodReportday(flag,reportDate,billFoodReportTableName);
//    }
}

















